package com.xb.cloud.common.util;

import java.io.File;
import java.io.InputStream;
import java.util.UUID;

import org.apache.commons.io.FilenameUtils;

import com.aliyun.oss.OSSClient;
import com.xb.cloud.common.constant.AliOssConfig;

public class SimpleUploadUtils {
//	private static final String endpoint = "http://oss-cn-shanghai.aliyuncs.com";
//	private static final String accessKeyId = "LTAIoKu0VMKqIjS7";
//	private static final String accessKeySecret = "iyEMrQdF1XtKvPTV45BvgSoiVKk77F";
//	private static final String bucketName = "xianbei-ticket";
//	private static final String bucketUrl = "http://image.xianbeitech.com";// http://xianbei-ticket.oss-cn-shanghai.aliyuncs.com

	private static OSSClient getOSSClient() {
		return new OSSClient(AliOssConfig.endpoint, AliOssConfig.accessKeyId, AliOssConfig.accessKeySecret);
	}

	private static String getUploadUrl(String fileName) {
		return AliOssConfig.bucketUrl + "/" + fileName;
	}

	public static String uploadUUIDName(String originalFilename, InputStream is) {
		String ext = FilenameUtils.getExtension(originalFilename);
		String fileName = UUID.randomUUID().toString() + "." + ext;
		OSSClient ossClient = getOSSClient();
		ossClient.putObject(AliOssConfig.bucketName, fileName, is);
		ossClient.shutdown();
		return getUploadUrl(fileName);
	}

	/**
	 * 上传文件
	 * 
	 * @param fileName
	 *            文件在服务器上的名称
	 * @param is
	 *            输入流
	 * @return 返回文件在服务器上的地址
	 */
	public static String upload(String fileName, InputStream is) {
		OSSClient ossClient = getOSSClient();
		ossClient.putObject(AliOssConfig.bucketName, fileName, is);
		ossClient.shutdown();
		return getUploadUrl(fileName);
	}

	/**
	 * 上传文件
	 * 
	 * @param file
	 *            本地文件
	 * @return 返回文件在服务器上的地址
	 */
	public static String upload(File file) {
		String fileName = file.getName();
		OSSClient ossClient = getOSSClient();
		ossClient.putObject(AliOssConfig.bucketName, fileName, file);
		ossClient.shutdown();
		return getUploadUrl(fileName);
	}

	/**
	 * 上传文件
	 * 
	 * @param fileName
	 *            文件在服务器上的名称
	 * @param file
	 *            本地文件
	 * @return 返回文件在服务器上的地址
	 */
	public static String upload(String fileName, File file) {
		OSSClient ossClient = getOSSClient();
		ossClient.putObject(AliOssConfig.bucketName, fileName, file);
		ossClient.shutdown();
		return getUploadUrl(fileName);
	}
}
